package com.haiyou.common.plugin.util;

import com.haiyou.common.plugin.model.Plugin;
import com.haiyou.common.plugin.service.PluginService;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

public class PluginManager {

    private URLClassLoader urlClassLoader;

    public PluginManager(List<Plugin> plugins) throws MalformedURLException {
        init(plugins);
    }

    private void init(List<Plugin> plugins) throws MalformedURLException {
        int size = plugins.size();
        URL[] urls = new URL[size];

        for (int i = 0; i < size; i++) {
            Plugin plugin = plugins.get(i);
            String filePath = plugin.getJar();
            urls[i] = new URL("file:" + filePath);
        }

        // 将jar文件组成数组，来创建一个URLClassLoader
        urlClassLoader = new URLClassLoader(urls);
    }

    public PluginService getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 插件实例化对象，插件都是实现PluginService接口
        Class<?> clazz = urlClassLoader.loadClass(className);
        Object instance = clazz.newInstance();

        return (PluginService) instance;
    }

    /**
     * 初始化插件
     */
    public static void initPlugin(String pluginPath) {
        try {
            List<Plugin> pluginList = XMLParser.getPluginList(pluginPath);
            PluginManager pluginManager = new PluginManager(pluginList);
            for (Plugin plugin : pluginList) {
                PluginService pluginService = pluginManager.getInstance(plugin.getClassName());
                System.out.println("开始执行[" + plugin.getName() + "]插件...");
                // 调用插件
                pluginService.service(plugin.getConfigs());
                System.out.println("[" + plugin.getName() + "]插件执行完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
